/*****************************************************************************
 * Aout.java
 *****************************************************************************/

package org.video.stream;

import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.util.Log;

public class Aout {
    /**
     * Java side of the audio output module for Android.
     * Uses an AudioTrack to play decoded audio buffers.
     */

    public Aout() {
    }

    private AudioTrack mAudioTrack;
    private static final String TAG = "corelib";

    public void init(int sampleRateInHz, int channels, int samples) {
        Log.d(TAG, sampleRateInHz + ", " + channels + ", " + samples + "=>" + channels * samples);
        int minBufferSize = AudioTrack.getMinBufferSize(sampleRateInHz,
                                                        (channels==2)?AudioFormat.CHANNEL_CONFIGURATION_STEREO:AudioFormat.CHANNEL_CONFIGURATION_MONO,
                                                        (samples==2)?AudioFormat.ENCODING_PCM_16BIT:AudioFormat.ENCODING_PCM_8BIT);
        Log.d(TAG, "minBufferSize=" + minBufferSize);
        mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
                                     sampleRateInHz,
                                     (channels==2)?AudioFormat.CHANNEL_CONFIGURATION_STEREO:AudioFormat.CHANNEL_CONFIGURATION_MONO,
                                     (samples==2)?AudioFormat.ENCODING_PCM_16BIT:AudioFormat.ENCODING_PCM_8BIT,
                                     minBufferSize,
                                     AudioTrack.MODE_STREAM);
    }

    public void release() {
        if (mAudioTrack != null) {
            mAudioTrack.release();
        }
        mAudioTrack = null;
    }

    public void playBuffer(byte[] audioData, int bufferSize) {
        if (mAudioTrack.write(audioData, 0, bufferSize) != bufferSize) {
            Log.w(TAG, "Could not write all the samples to the audio device");
        }
        mAudioTrack.play();
    }
}
